package lcof;

import pojo.ListNode;

import java.util.Stack;
import java.util.ArrayList;

/**
 * @author 江岸
 * @version V1.0
 * @ClassName: ReversePrint6
 * @description: 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 * @date 2021/2/2413:58
 * @since V1.0
 */
public class ReversePrint6 {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        ListNode temp=head;
        while (temp!=null){
            stack.push(temp.val);
            temp = temp.next;
        }
        int[] ints = new int[stack.size()];
        int i=0;
        while (!stack.empty()){
            ints[i] = stack.pop();
            i++;
        }
        return ints;
    }

    //递归

    ArrayList<Integer> tmp = new ArrayList<Integer>();

    public int[] reversePrint2(ListNode head) {
        recur(head);
        int[] res = new int[tmp.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = tmp.get(i);
        return res;
    }
    void recur(ListNode head) {
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }

}
